using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
using UnityEngine.EventSystems;

public class Card : MonoBehaviour, IPointerClickHandler
{
    private int value;
    private bool isFlipped = false;
    private bool isMatched = false;
    private float aniDuration = 0.2f;
    private bool isAnimating = false;
    private GameManager gm;
    
    void Start()
    {
        gm = GameManager.Instance;
    }

    public void Init(int cardValue, float width, float height, Sprite sprite)
    {
        value = cardValue;
        RectTransform rt = GetComponent<RectTransform>();
        rt.sizeDelta = new Vector2(width, height);
        Image frontImg = transform.Find("Front").GetComponent<Image>();
        frontImg.sprite = sprite;
    }
    
    public void Flip()
    {
        isFlipped = !isFlipped;
        isAnimating = true;
        if (isFlipped)
        {
            transform.DORotate(new Vector3(0f, 180f, 0f), aniDuration)
                .SetEase(Ease.Linear)
                .OnComplete(() => isAnimating = false);
            gm.MatchFlipCard(this);
        }
        else
        {
            transform.DORotate(new Vector3(0f, 0f, 0f), aniDuration)
                .SetEase(Ease.Linear)
                .OnComplete(() => isAnimating = false);
        }
    }
    
    public void OnPointerClick(PointerEventData eventData)
    {
        // 已翻牌 | 已匹配 | 动画中 不可翻牌
        if (isFlipped || isMatched || isAnimating) return;
        Flip();
    }
    
    public int GetValue()
    {
        return value;
    }
    
    public void SetIsMatched()
    {
        isMatched = true;
    }

}
